﻿//////////////////////////////////////////////////////////////////////////
/// Copyright (C), 1998-2016, rytec Corporation. All rights reserved.
/// \file       SortFilterProxyModel.cpp
/// \brief      
/// \author     wyf
/// \version    0.95
/// \date       2020-9
//////////////////////////////////////////////////////////////////////////
#include "SortFilterProxyModel.h"
#include "FilterHeaderView.h"

CRySortFilterProxyModel::CRySortFilterProxyModel(QObject* parent)
    : QSortFilterProxyModel(parent)
{
}

bool CRySortFilterProxyModel::setHeaderData(int section, Qt::Orientation orientation,
    const QVariant& value, int role)
{
    if (role == FILTER_REGEXP_ROLE)
        mFilterRegExps.insert(section, value.value<QRegExp>());
    return QSortFilterProxyModel::setHeaderData(section, orientation, value, role);
}

bool CRySortFilterProxyModel::filterAcceptsRow(int sourceRow, const QModelIndex& sourceParent) const
{
    if (isFilterRegExpsEmpty())
        return true;

    if (mFilterRegExps.size() == 1)
    {
        return QSortFilterProxyModel::filterAcceptsRow(sourceRow, sourceParent);
    }
    else
    {
        QMap<int, QRegExp>::const_iterator cit = mFilterRegExps.begin();
        for (; cit != mFilterRegExps.end(); ++cit)
        {
            QModelIndex sourceIndex = sourceModel()->index(sourceRow, cit.key(), sourceParent);
            QString key = sourceModel()->data(sourceIndex, filterRole()).toString();
            if (!key.contains(cit.value()))
                return false;
        }
        return true;
    }
}

bool CRySortFilterProxyModel::isFilterRegExpsEmpty() const
{
    if (mFilterRegExps.isEmpty())
        return true;

    QMap<int, QRegExp>::const_iterator cit = mFilterRegExps.begin();
    for (; cit != mFilterRegExps.end(); ++cit)
    {
        if (!cit->isEmpty())
            return false;
    }
    return true;
}
